/*
 * properties-parse.cpp
 *
 *  Created on: 12.03.2013
 *      Author: SomeChineseGuy
 */

#include <string>
#include <string.h>
#include <vector>
#include <fstream>
#include <iostream>

#include "properties-parse.h"

using namespace std;

PropertiesParser::PropertiesParser(char* fname) {

	filename = new char;

	filename = strcpy(filename, fname);
	cout<<"BOO!"<<endl;

}

PropertiesParser::~PropertiesParser() {
	//delete filename;
	clearList();
}

int PropertiesParser::parseProperties() {

	ifstream* propFile = new ifstream();
	propFile->open(filename, ios::in);

	if (!propFile->is_open()) {
		return 1;
	}
	clearList();
	string* line = new string();
	propFile->seekg(ios::beg);

	while (propFile->good()) {
		getline(*propFile, *line);
		if (line->at(0) != '#') {
			propertyPair* newPair = new propertyPair();
			if ((line->find('=') != line->npos) && (line->find('=') != 0)) {
				newPair->name = line->substr(0, line->find('='));
				newPair->value =
						(line->find('=') == line->size() - 1) ?
								"" :
								line->substr(line->find('=') + 1,
										line->size() - 1);

				list.insert(list.begin(), newPair);
			}
		}
	}

	propFile->close();
	delete propFile;

	return 0;
}

void PropertiesParser::clearList() {
	for (unsigned int i = 0; i < list.size(); i++) {
		delete list.at(i);
	}
	list.clear();
}

char* PropertiesParser::getPropertyByName(char* name) {
	char* result = NULL;

	string* propName;

	for (unsigned int i = 0; i < list.size(); i++) {

		propertyPair* pair = list.at(i);
		propName = new string(pair->name);

		if (propName->compare((char*) name) == 0) {
			result = new char;
			strcpy(result, pair->value.c_str());
		}
	}

	delete propName;
	return result;
}
